package com.meitianhui.convenitenbuy.widget.wheelview;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.widget.wheelview.adapter.ArrayWheelAdapter;
import com.meitianhui.convenitenbuy.widget.wheelview.bean.TimeInfo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * 时间选择
 * Created by liuwy on 2015/12/25.
 */
public class TimeSelectorPopWindow implements View.OnClickListener,
        OnWheelChangedListener {


    private TextView tvTime, tvInfo;

    /**
     * 主布局
     */
    private View containerView;

    private PopupWindow mPopupWindow;

    /**
     * 当前日期索引
     */
    private int curDatetIndex;

    /**
     * 当前小时索引
     */
    private int curHourdIndex;

    /**
     * 当前时分索引
     */
    private int curMinuteIndex;


    /**
     * 结果回调监听
     */
    private DateSelectorPopWindowListener mListener;


    /**
     * 可见项
     */
    private static int WHELLVIEW_VISIBLE_ITEM = 7;


    /**
     * 上下文
     */
    protected Context mContext;

    /**
     * 第一列 WheelView
     */
    protected WheelView mFirstWheelView;

    /**
     * 第二列 WheelView
     */
    protected WheelView mSecondWheelView;

    /**
     * 第三列 WheelView
     */
    protected WheelView mThirdWheelView;

    /**
     * 第一列 WheelView数据适配器
     */
    protected ArrayWheelAdapter mFirstWheelViewAdapter;

    /**
     * 第二列 WheelView数据适配器
     */
    protected ArrayWheelAdapter mSecondWheelViewAdapter;

    private ArrayWheelAdapter mThridWheelViewAdapter;

    /**
     * 确定按钮
     */
    private Button mConfirmBtn;

    /**
     * 取消按钮
     */
    private Button mCancleBtn;


    /**
     * 第一列日期数据集
     */
    public List<TimeInfo> mDatetList;

    /**
     * 第二列时数据集
     */
    public List<TimeInfo> mHourdList;

    /**
     * 第三列分数据集
     */
    public List<TimeInfo> mMinuteList;


    /**
     * 默认长度为7
     */
    private int defaultMaximumLength = 13;

    /**
     * 字体大小
     */
    private int textSize = 15;


    public TimeSelectorPopWindow(TextView tvTime, TextView tvInfo, Context mContext, DateSelectorPopWindowListener mListener) {
        this.tvTime = tvTime;
        this.tvInfo = tvInfo;
        this.mContext = mContext;
        this.mListener = mListener;
        initView();

        loadData();
        init();
    }

    private void loadData() {
        mFirstWheelView.setVisibleItems(WHELLVIEW_VISIBLE_ITEM);
        mSecondWheelView.setVisibleItems(WHELLVIEW_VISIBLE_ITEM);
        mThirdWheelView.setVisibleItems(WHELLVIEW_VISIBLE_ITEM);

        mDatetList = new ArrayList<TimeInfo>();
        mHourdList = new ArrayList<TimeInfo>();
        mMinuteList = new ArrayList<TimeInfo>();
        initTimeData();
        initAdapter();
    }


    /**
     * 初始化适配器
     */
    public void initAdapter() {
        if (mDatetList != null && mHourdList != null && mMinuteList != null) {
            mFirstWheelViewAdapter = new ArrayWheelAdapter(mContext, mDatetList.toArray(new Object[mDatetList.size()]));
            mSecondWheelViewAdapter = new ArrayWheelAdapter(mContext, mHourdList.toArray(new Object[mHourdList.size()]));
            mThridWheelViewAdapter = new ArrayWheelAdapter(mContext, mMinuteList.toArray(new Object[mMinuteList.size()]));
            mFirstWheelView.setViewAdapter(mFirstWheelViewAdapter);
            mSecondWheelView.setViewAdapter(mSecondWheelViewAdapter);
            mThirdWheelView.setViewAdapter(mThridWheelViewAdapter);
        }
    }

    public View getContainerView() {
        return containerView;
    }

    public void setContainerView(View containerView) {
        this.containerView = containerView;
    }

    private void initView() {
        containerView = LayoutInflater.from(mContext).inflate(
                R.layout.wheels_layout, null);

        mFirstWheelView = (WheelView) containerView
                .findViewById(R.id.date_wheelView);
        mSecondWheelView = (WheelView) containerView
                .findViewById(R.id.periodTime_wheelView);
        mThirdWheelView = (WheelView) containerView
                .findViewById(R.id.time_wheelView);
        mConfirmBtn = (Button) containerView.findViewById(R.id.btn_confirm);
        mCancleBtn = (Button) containerView.findViewById(R.id.btn_cancle);
//        // 设置显示的字体大小
//        mFirstWheelView.setTextSize(textSize);
//        mSecondWheelView.setTextSize(textSize);
//        mThirdWheelView.setTextSize(textSize);
        // // 设置循环
        mFirstWheelView.setCyclic(true);
        mSecondWheelView.setCyclic(true);
        mThirdWheelView.setCyclic(true);
        mConfirmBtn.setOnClickListener(this);
        mCancleBtn.setOnClickListener(this);
    }

    /**
     * 初始化方法
     */
    private void init() {
        mPopupWindow = new PopupWindow(getContainerView(),
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setAnimationStyle(R.style.BottomDialogMenuAnim);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(false);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPopupWindow.dismiss();
            }
        });
    }

    private void dissMiss() {
        tvTime.setText(mFirstWheelViewAdapter.getItemText(curDatetIndex) +
                "-" + mSecondWheelViewAdapter.getItemText(curHourdIndex) + "-"
                + mThridWheelViewAdapter.getItemText(curMinuteIndex));
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_confirm) {
            if (callBackDate()) {
                mPopupWindow.dismiss();
            }
        } else if (id == R.id.btn_cancle) {
            mPopupWindow.dismiss();
        }
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // 日期滑动事件处理
        if (wheel == mFirstWheelView) {
            if (newValue == 0) {// 当日期索引为第一项时(即当天时间，更新限制时间)
                mHourdList.clear();
//                mHourdList.addAll(getHourList(false));
//                mSecondWheelView.notifyDataSetChanged();
                curHourdIndex = 0;
                setSecondCurrentItem(curHourdIndex);
            } else if (oldValue == 0) {// 当滑出日期第一项时，重新更新不限制时间
                mHourdList.clear();
//                mHourdList.addAll(getHourList(false));
//                mSecondWheelView.notifyDataSetChanged();
            }
        }
    }

    /**
     * 回调日期数据
     *
     * @return 成功回调返回true
     */
    private boolean callBackDate() {
        if (mListener != null) {
            curDatetIndex = mFirstWheelView.getCurrentItem();
            curHourdIndex = mSecondWheelView.getCurrentItem();
            curMinuteIndex = mThirdWheelView.getCurrentItem();
            StringBuilder sBuffer = new StringBuilder();
            if (mDatetList != null && mDatetList.size() > 0
                    && mHourdList != null && mHourdList.size() > 0
                    && mMinuteList != null && mMinuteList.size() > 0) {
                // 拼接时间
                sBuffer.append(mDatetList.get(curDatetIndex));
                sBuffer.append("年");
                sBuffer.append(mHourdList.get(curHourdIndex));
                sBuffer.append("月");
                sBuffer.append(mMinuteList.get(curMinuteIndex));
                sBuffer.append("日");

                tvTime.setText(mFirstWheelViewAdapter.getItemText(curDatetIndex) +
                        "-" + mSecondWheelViewAdapter.getItemText(curHourdIndex) + "-"
                        + mThridWheelViewAdapter.getItemText(curMinuteIndex));
            }

            String dateStr = sBuffer.toString();
            long dateMiliis = getDateMillis(dateStr);
            // 结果回调
            mListener.onSelectDate(dateStr, dateMiliis);
            return true;
        }
        return false;
    }

    /**
     * 获取时间格式
     *
     * @return
     */
    private SimpleDateFormat getSimpleDateFormat() {
        return new SimpleDateFormat("yyyy年MM月dd日");
    }

    /**
     * 获取当前日期毫秒数
     *
     * @param dateStr
     * @return
     */
    private long getDateMillis(String dateStr) {
        Calendar calendar = new GregorianCalendar();
        try {
            Date date = getSimpleDateFormat().parse(dateStr);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return calendar.getTimeInMillis();
    }

    /**
     * 初始化时间当前时间
     *
     * @ curDatetIndex  当前日期索引
     * @ curHourdIndex  当前小时索引
     * @ curMinuteIndex 当前时分索引
     */
    public void initDate(int datetIndex, int hourdIndex, int minuteIndex) {
        if (datetIndex < mDatetList.size() && hourdIndex < mHourdList.size()
                && minuteIndex < mMinuteList.size()) {
            this.curDatetIndex = datetIndex;
            this.curHourdIndex = hourdIndex;
            this.curMinuteIndex = minuteIndex;
            setFirstCurrentItem(curDatetIndex);
            setSecondCurrentItem(curHourdIndex);
            setThirdCurrentItem(curMinuteIndex);
//          callBackDate();
        }
    }

    /**
     * 设置回调监听器
     */
    public void setDateSelectorPopWindowListener(
            DateSelectorPopWindowListener listener) {
        this.mListener = listener;
    }

    /**
     * DateSelector监听器
     */
    public interface DateSelectorPopWindowListener {
        /**
         * 选择的日期
         *
         * @param dateStr 日期字符串
         * @param date    日期毫米数
         */
         void onSelectDate(String dateStr, long date);
    }

    /**
     * 显示
     *
     * @param v
     */
    public void show(View v) {
        mPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        // notifyDataSetChanged();
        setFirstCurrentItem(curDatetIndex);
        setSecondCurrentItem(curHourdIndex);
        setThirdCurrentItem(curMinuteIndex);
    }

    /**
     * 设置第一列WheelView索引
     *
     * @param index
     */
    public void setFirstCurrentItem(int index) {
        mFirstWheelView.setCurrentItem(index);
    }

    /**
     * 初始化时间
     */
    private void initTimeData() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        // 年
        for (int i = 1; i < 120; i++) {
            year = calendar.get(Calendar.YEAR);
            TimeInfo time = new TimeInfo();
            time.setTimeType(1);
            time.setId(year);
            time.setTimeStr(year + "");
            mDatetList.add(time);
            calendar.add(Calendar.YEAR, -1);
        }
        // 月
        for (int i = 1; i < 13; i++) {
            TimeInfo time = new TimeInfo();
            time.setTimeType(2);
            time.setTimeStr(i > 9 ? i + "" : "0" + i);
            time.setId(i);
            mHourdList.add(time);
        }
        // 日
        refreshDate(year, month);
    }

    /**
     * 根据年与月刷新日期
     */
    private void refreshDate(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, 0);
        mMinuteList.clear();
        for (int i = 1, maxDate = calendar
                .getActualMaximum(Calendar.DAY_OF_MONTH); i <= maxDate; i++) {
            TimeInfo time = new TimeInfo();
            time.setTimeValue(i);
            time.setId(i);
            time.setTimeStr(i > 9 ? i + "" : "0" + i);
            mMinuteList.add(time);
        }
        mThirdWheelView.setCurrentItem(15);
    }

    /**
     * 设置第二列WheelView索引
     *
     * @param index
     */
    public void setSecondCurrentItem(int index) {
        mSecondWheelView.setCurrentItem(index);
    }

    /**
     * 设置第三列WheelView索引
     *
     * @param index
     */
    public void setThirdCurrentItem(int index) {
        mThirdWheelView.setCurrentItem(index);
    }
}
